const userdb = require('../db/userdb')
const { QueryTypes } = require('sequelize');

exports.deleteUser = async function (id) {
    let result;
    if (id) {
        result = await userdb.sequelize.query(`update userdb set status = '冻结' where id = '${id}';`);
    } else if (!id) {
        return false;
    }
    return result;
}


exports.setAdmin = async function (id) {
    let result;
    if (id) {
        result = await userdb.sequelize.query(`update  userdb set role="管理员" where id = '${id}';`);

    } else if (!id) {
        return false;
    }
    return result;
}

exports.getAllUsers = async function (user,pageNo) {
    let users;
    let counts;

    if (user) {
        users = await userdb.sequelize.query(`select * from (select * from userdb where username like '%${user}%' or id like '%${user}%' ) as getAllUsers limit  ${(pageNo-1)*10}, 10;`, { type: QueryTypes.SELECT });
        counts = await userdb.sequelize.query(`select count(*) as counts from (select * from userdb where username like '%${user}%' or id like '%${user}%'  ) as smallTbale;`, { type: QueryTypes.SELECT });
        

    } else if (!user) {
        users = await userdb.sequelize.query(`select * from userdb limit 0, 10;`, { type: QueryTypes.SELECT });
        counts = await userdb.sequelize.query("select count(*) as counts from userdb ;", { type: QueryTypes.SELECT });
        
    }else{
        return false;
    }
    return {
        users,
        counts
    };
}

exports.getPageUsers = async function (pageNo) {
    let users;
    let counts;
    if (pageNo>=0) {
        users = await userdb.sequelize.query(`select * from userdb limit  ${(pageNo-1)*10}, 10;`, { type: QueryTypes.SELECT });
        counts = await userdb.sequelize.query("select count(*) as counts from userdb ;", { type: QueryTypes.SELECT });
    } else if (pageNo<0) {
        return false;

    }
    return {
        users,
        counts
    };
}

exports.login = async function (loginid) {
    const users = await userdb.sequelize.query(`select * from userdb where id=${loginid}`, { type: QueryTypes.SELECT });
    return users;

}

exports.registe = async function (username, password) {
    const newUser = await userdb.create({ username: username, userpassword: password });
    return newUser;
}

async function alter(loginid, newPwd) {
    let res = await userdb.sequelize.query(
        `update userdb set userpassword = '${newPwd}' where id = ${loginid}`
    )
    return res;
}

// 修改密码，传入loginid和newPwd
exports.alterPwd = async function (loginid, oldPwd, newPwd) {
    let result = await userdb.sequelize.query(
        `select userpassword from userdb where id = ${loginid} `, { type: QueryTypes.SELECT }
    ).then((res) => {
        if (res[0].userpassword != oldPwd) {
            return false;
        } else if (res[0].userpassword == oldPwd) {
            alter(loginid, newPwd)
            return true;
        }
    });



    return result;
}